package com.ls.day11;

import com.ls.day2.ListNode;

public class ReverseKGroup {

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
//        ListNode l3 = new ListNode(3);
//        ListNode l4 = new ListNode(4);
//        ListNode l5 = new ListNode(5);
        l1.next=l2;
//        l2.next=l3;
//        l3.next=l4;
//        l4.next=l5;
        ListNode L = reverseKGroup(l1,2);
        while (L!=null){
            System.out.print(L.val+" ");
            L=L.next;
        }
    }

    public static ListNode reverseKGroup(ListNode head, int k) {
        int count=0;
        ListNode list = new ListNode();
        ListNode front_node = list;
        ListNode flag = head,p=head,tem;
        if (k==1) return head;
        while (checkK(flag,k)){       //从前驱节点开始往后还有k个节点
            count=k;
            while (count>0){        //头插法完成
                count--;
                tem = p;
                p=p.next;
                tem.next=front_node.next;
                front_node.next=tem;
            }
            front_node=flag;
            front_node.next=p;
            flag=p;
        }
        return list.next;
    }

    public static boolean checkK(ListNode n,int k){
        if (n==null)return false;
        while (k>1){
            n=n.next;
            k--;
            if (n==null)return false;
        }
        return true;
    }
}
